package com.java.simple.study.juc;

import cn.hutool.core.thread.ThreadUtil;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;

/**
 * @author zhoujunlin
 * @date 2023年04月13日 10:34
 * @desc
 */
public class AsyncTest {

    public static void main(String[] args) {
//        testCompleteFuture();
//        testThreadUtil();
        testListenable();
    }

    public static void testListenable() {
        // 异步任务完成监听
        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("callable execute...");
                TimeUnit.SECONDS.sleep(1);
                return 1;
            }
        });


        Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer result) {
                //成功执行...
                System.out.println("Get listenable future's result with callback " + result);
            }

            @Override
            public void onFailure(Throwable t) {
                //异常情况处理...
                t.printStackTrace();
            }
        });

    }


    public static void testThreadUtil() {
        ThreadUtil.execAsync(() -> {
            System.out.println("111111");
        });
    }


    @SneakyThrows
    public static void testCompleteFuture() {
        // 异步任务流   cf1->cf2  公用一个线程池一个线程
        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getId() + " cf1 do something! ");
            return 1;
        });

        CompletableFuture<Void> cf2 = cf1.thenRunAsync(() -> {
            System.out.println(Thread.currentThread().getId() + " cf2 do something! ");
        });

        System.out.println("cf1结果：" + cf1.get());
        System.out.println("cf2结果：" + cf2.get());

    }


}
